<template>
  <el-card>
    <el-row class="custom-row">
      <el-col :span="5">
        <el-input placeholder="请输入要搜索的仓库编号" clearable v-model="queryForm.queryById"></el-input>
      </el-col>
      <el-col :span="2.5">
        <el-button type="primary" @click="handleSearchById">按编号搜索</el-button>
      </el-col>
      <el-col :span="5">
        <el-input placeholder="请输入要搜索的仓库名字" clearable v-model="queryForm.queryByName"></el-input>
      </el-col>
      <el-col :span="2.5">
        <el-button type="primary" @click="handleSearchByName">按名称搜索</el-button>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="dialogVisible = true">添加仓库</el-button>
      </el-col>
    </el-row>

    <el-table :data="tableData" style="width: 100%" height="600">
      <el-table-column fixed prop="wareId" label="仓库编号" width="150" />
      <el-table-column prop="wareName" label="仓库名字" width="150" />
      <el-table-column prop="warePhone" label="联系电话" width="150" />
      <el-table-column prop="wareTon" label="仓库容量" width="150" />
      <el-table-column prop="wareFreeDay" label="仓库免费天数" width="150" />
      <el-table-column prop="wareManger" label="仓库管理员" width="150" />
      <el-table-column prop="wareRate" label="仓库利率/天/吨" />
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">修改</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="仓库信息" v-model="dialogVisible" width="30%">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="仓库名字">
          <el-input v-model="editForm.wareName"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="editForm.warePhone"></el-input>
        </el-form-item>
        <el-form-item label="仓库容量">
          <el-input v-model="editForm.wareTon"></el-input>
        </el-form-item>
        <el-form-item label="仓库免费天数">
          <el-input v-model="editForm.wareFreeDay"></el-input>
        </el-form-item>
        <el-form-item label="仓库管理员">
          <el-input v-model="editForm.wareManger"></el-input>
        </el-form-item>
        <el-form-item label="仓库利率/天/吨">
          <el-input v-model="editForm.wareRate"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddOrUpdate">确定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref } from 'vue';
import axios from '~/api/request.js';

const dialogVisible = ref(false);
const tableData = ref([]);




const handleSearchById = async () => {
  try {
    const response = await axios.get(`/api/ware/selectWareById/${queryForm.value.queryById}`);
    console.log('Response from API:', response.data); // Check response object
    if (response && response.data!==null) {
      tableData.value = [response.data.data];
      console.log('Ware found:', response.data); // 输出查找成功的信息
    }  else {
      console.error('Ware not found or response data is invalid:', response.data);
    }
  } catch (error) {
    console.error('Error searching ware by ID:', error);
    // 可以根据 error.response 的状态码来进一步处理不同类型的错误
  }
};

const handleSearchByName = async () => {
  try {
    const response = await axios.get(`/api/ware/selectWareByName/${queryForm.value.queryByName}`);
    console.log('Response from API:', response); // Check response object
    if (response && response.data) {
      console.log('Data received:', response.data); // Check received data
      tableData.value = response.data.data; // Update tableData.value
    } else {
      console.error('Empty response or missing data in response.');
    }
  } catch (error) {
    console.error('Error searching warehouses by name:', error);
  }
};



const handleEdit = (row) => {
  editForm.value = { ...row };
  dialogVisible.value = true; // 显示对话框
};
const handleAddOrUpdate = async () => {
  try {
    let endpoint = '/api/ware/add';
    if (editForm.value.wareId) {
      endpoint = '/api/ware/update';
    }

    const response = await axios.post(endpoint, editForm.value);

    if (response.status === 200) {
      // 处理成功情况
      dialogVisible.value = false;
      editForm.value = { // Clear only after successful submission
        wareName: '',
        wareRate: '',
        wareTon: '',
        wareFreeDay: '',
        wareManger: '',
        warePhone: ''
      };
      loadData(); // Assuming you have a function to reload data
    } else {
      // 处理失败情况
      console.error('操作失败');
    }
  } catch (error) {
    console.error('操作失败', error);
  }
};




const handleDelete = async (row) => {
  try {
    // 构建请求 URL，使用字符串模板来替换 {row.wareId}


    // 发送删除请求
    const response = await axios.post(`/api/ware/delete/${row.wareId}`);

    // 检查后端是否返回成功的消息，这里假设返回状态码或者成功消息
    if (response.status === 200) {
      // 更新前端数据，这里假设 tableData 是响应式数据
      const index = tableData.value.findIndex(item => item.wareId === row.wareId);
      if (index !== -1) {
        tableData.value.splice(index, 1); // 从表格数据中移除被删除的行
      }
      // 提示用户删除成功，可以使用消息框或通知组件
      // 这里可以添加一些提示用户删除成功的逻辑
    } else {
      console.error('删除仓库失败');
      // 可以添加一些提示用户删除失败的逻辑
    }
  } catch (error) {
    console.error('删除仓库失败', error);
    // 可以添加一些提示用户删除失败的逻辑
  }
};



// 页面加载时自动加载数据
const loadData = async () => {

  const res = await axios.get("/api/ware/selectAllWare")
    .then(res => {
      console.log(res.data);
      tableData.value = res.data.data
    })




};

const resetForms = () => {
  addForm.value = {}; // 清空addForm
  editForm.value = null; // 清空editForm
};


const addForm = ref({
  wareName: '',
  wareRate: '',
  wareTon: '',
  wareFreeDay: '',
  wareManger: '',
  warePhone: '',
});

const queryForm = ref({
  query: '',
  pagenum: '1',
  pagesize: '10',
  queryById: '',
  queryByName: ''
});

const editForm = ref({
  wareId:'',
  wareName: '',
  wareRate: '',
  wareTon: '',
  wareFreeDay: '',
  wareManger: '',
  warePhone: '',
  
}); 


// 页面加载时调用加载数据函数
import { onMounted } from 'vue';
onMounted(loadData);

</script>

<style>
.distance {
  padding-bottom: 16px;
  box-sizing: border-box;
}
.custom-row {
  margin-left: -10px; /* 负 margin 补偿列之间的间隙 */
  margin-right: -10px;
}

.custom-row .el-col {
  padding-left: 10px; /* 调整列的 padding */
  padding-right: 10px;
}
</style>
